#完成底层的封装，find方法
import os
import time

from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.webdriver import WebDriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
import datetime
from logs.logger import Logger
from data_file_analysis.yaml_analysis import YamlAnalysis as ya
from selenium.webdriver.support.wait import WebDriverWait

class Base():
    _black_list = [(By.ID, 'iv_close')]
    _error_count = 0
    _error_max = 10
    _verify_result = ''
    cur_path = os.path.abspath(os.path.dirname(__file__))  # 获取当前文件目录
    root_path = os.path.dirname(cur_path)
    time_now = datetime.datetime.now()
    time_now1 = f'{str(time_now.year)}_{str(time_now.month)}_{str(time_now.day)}_{str(time_now.hour)}_{str(time_now.minute)}'
    log = Logger(f'{root_path}/logs/info/{time_now1}_info.log', level='info')

    def __init__(self, driver:WebDriver = None):
        self.driver = driver
        driver.implicitly_wait(5)

    def steps(self, file_path, page_action, params: dict = None):
        steps: list[dict] = ya.return_yaml_data(file_path, page_action)
        self.log.logger.info(f'{page_action}:')

        for step in steps:

            # 日志打印
            self.log.logger.info(f"by_type:{step['by']}, locator:{step['locator']}")

            if 'value' in step.keys():
                self.log.logger.info(f"value:{step['value']}")

            if 'action' in step.keys():
                if 'sleep' == step['action']:
                    time.sleep(3)

                elif 'click' == step['action']:
                    if 'by' in step.keys():
                        if step['by'] == 'scroll_element':
                            element = self.scroll_element(step['locator'])
                            element.click()
                        else:
                            self.ele_click(step['by'], step['locator'])
                    else:
                        raise Exception

                elif 'send' == step['action']:
                    self.ele_send_keys(step['by'], step['locator'], step['value'], params)

                elif 'radio_click' == step['action']:
                    self.radio_click(step['by'], step['locator'], step['value'], params)

                elif 'switch_to_frame' == step['action']:
                    self.switch_to_frame(step['by'], step['locator'])

                elif 'js_execute' == step['action']:
                    self.js_execute(step['by'], step['locator'], step['value'], params)

                else:
                    raise Exception
            else:
                raise Exception

    #@black_wrapper
    def find(self, by_type, locator):
        self.driver.implicitly_wait(10)
        return self.driver.find_element(by_type, locator)

    def finds(self, by_type, locator):
        self.driver.implicitly_wait(10)
        return self.driver.find_elements(by_type, locator)

    def ele_click(self, by_type, locator):
        element = self.find(by_type, locator)
        element.click()

    #赋值
    def ele_send_keys(self, by_type, locator, value, params):
        '''
        1.命中规则：传入的参数为键值对，且已给params赋值，步骤里文件里的value命中params的键值来命中
        2.content_key:获取步骤value的值
        3.根据content_key匹配_param_list的键值，将获取的参数赋值给content
        4.将content内容send_keys到对应元素的文本框
        '''
        content_key = value
        content = params[content_key]

        self.log.logger.info(f"{content_key}:{content}")

        self.find(by_type, locator).send_keys(content)

    #单选框
    def radio_click(self, by_type, locator, value, params):
        content_key = value
        content = params[content_key]

        self.log.logger.info(f"{content_key}:{content}")

        radios = self.finds(by_type, locator)
        for radio in radios:
            if radio.get_attribute('value') == str(content):
                radio.click()

    #跳转到窗口
    def switch_to_frame(self, by_type, locator):
        element = self.find(by_type, locator)
        self.driver.switch_to.frame(element)

    #多选框
    def checkbox_click(self, by_type, locator):
        pass

    #ActionChains操作
    def action_chains_click(self, by_type, locator):
        element = self.driver.find_element(by_type, locator)
        action = ActionChains(self.driver)
        action.move_to_element(element)
        action.click(element)
        action.perform()

    def scroll_element(self, text):
        ui_text = f'new UiScrollable(new UiSelector().scrollable(true).instance(0)).' \
                  f'scrollIntoView(new UiSelector().text("{text}").instance(0))'
        ele = self.driver.find_element(MobileBy.ANDROID_UIAUTOMATOR, ui_text)
        return ele

    #返回上一层目录
    def goback(self):
        self.driver.back()

    #显式等待
    def webdriver_wait(self, by_type, locator):
        WebDriverWait(self.driver, 5).until(lambda driver : self.find(by_type, locator))

    #执行JavaScript脚本
    def js_execute(self, by_type, locator,  value, params):
        content_key = value
        content = params[content_key]

        self.log.logger.info(f"{content_key}:{content}")

        if by_type == 'id':
            js_set = f'document.getElementById({locator}).value={content};'

        self.driver.execute_script(js_set)





